<template>
  <el-form :inline="true" class="user-search">
    <el-form-item label="搜索："> </el-form-item>
    <el-form-item label="" v-for="(item, index) in copy_props.data" :key="item.key">
      <template v-if="item.type === 'select'" v-show="item.showVerfiy ? showVerfiy(item) : true">
        <el-select
          clearable
          :placeholder="item.placeholder"
          v-model="queryData[item.key]"
          @change="change"
        >
          <el-option
            v-for="(optionItem, idx) in item.data"
            :key="idx"
            :label="optionItem.name"
            :value="optionItem.value"
          />
        </el-select>
      </template>

      <template v-else-if="item.type === 'date'">
        <el-date-picker
          v-model="queryData[item.key]"
          type="date"
          :placeholder="item.placeholder"
          :format="item.format"
          :value-format="item.valueFormat"
          @input="change"
          style="width: 100%"
        />
      </template>

      <template v-else-if="item.type === 'input-group'">
        <cInputGroup
          :ref="'inputGroup'"
          :style="`width:${item.width ? item.width + 'px' : '100%'}`"
          :value="formatInputGroup(item.value)"
          @emitValue="emitValue"
        />
      </template>

      <template v-else-if="item.type === 'cascader'">
        <el-cascader
          :placeholder="item.placeholder"
          clearable
          size="small"
          class="common-input"
          v-model="queryData[item.key]"
          :options="item.data"
          :props="item.props"
          @change="change"
        />
      </template>

      <template v-else>
        <el-input
          class="common-input"
          clearable
          size="small"
          :placeholder="item.placeholder"
          v-model.trim="queryData[item.key]"
          @input="change"
        />
      </template>
    </el-form-item>

    <el-form-item v-for="(item, index) in copy_props.btn" :key="index">
      <template v-if="item.type === 'search'">
        <el-button
          size="small"
          type="primary"
          icon="el-icon-search"
          @click.native="search"
        >搜索</el-button>
      </template>
      <template v-else>
        <el-button
          size="small"
          :type="item.style"
          :icon="item.icon"
          v-if="typeof item?.isShow === 'function'?item.isShow():item.isShow"
          @click.native="btnEvent(item)"
        >{{ item.label }}</el-button>
      </template>
    </el-form-item>
  </el-form>
</template>

<script>
import cInputGroup from '@/components/Search/input-group'
import cloneDeep from 'lodash/cloneDeep';

export default {
  name: 'cSearch',
  components: { cInputGroup },
  props: {
    search_props: {
      type: Object,
      required: true,
      default: () => ({}),
    },
  },
  data() {
    return {
      copy_props: {},
      queryData: {},
    }
  },
  watch: {
    search_props: {
      handler(newVal) {
        // 改成cloneDeep 避免丢失函数
        this.copy_props = cloneDeep(newVal)
        this.queryData = {}

        if (this.copy_props.data && Array.isArray(this.copy_props.data)) {
          for (const iterator of this.copy_props.data) {
            if (iterator.key) {
              if (iterator.query !== undefined) {
                this.$set(this.queryData, iterator.key, iterator.query)
              } else if (iterator.default !== undefined) {
                this.$set(this.queryData, iterator.key, iterator.default)
              } else {
                this.$set(this.queryData, iterator.key, null)
              }
            }

            if (iterator.type === 'input-group' && Array.isArray(iterator.value)) {
              for (const element of iterator.value) {
                if (element.key) {
                  if (element.query !== undefined) {
                    this.$set(this.queryData, element.key, element.query)
                  } else if (element.default !== undefined) {
                    this.$set(this.queryData, element.key, element.default)
                  } else {
                    this.$set(this.queryData, element.key, null)
                  }
                }
              }
            }

            // 异步请求填充 select options
            if (iterator.type === 'select' && iterator.url) {
              this.$http(iterator.url.method, iterator.url.api).then((res) => {
                const data = res.data.map((r) => ({
                  value: r[iterator.url.map.key],
                  name: r[iterator.url.map.value],
                }))
                this.$set(iterator, 'data', data)
              })
            }
          }
        }

        // 按钮数组处理
        if (!this.copy_props.btn) {
          this.$set(this.copy_props, 'btn', [])
        }
      },
      immediate: true,
      deep: true,
    },
  },

  
  methods: {
    showVerfiy(item) {
      return item.showVerfiy?.func ? item.showVerfiy.func() : true
    },
    formatInputGroup(value) {
      (value || []).forEach((element) => {
        if (element.type === 'select' && element.url) {
          this.$http(element.url.method, element.url.api).then((res) => {
            const data = res.data.map((r) => ({
              value: r[element.url.map.key],
              name: r[element.url.map.value],
            }))
            this.$set(element, 'data', data)
          })
        }
        this.$set(this.queryData, element.key, element.query !== undefined ? element.query : element.default)
      })
      return value
    },
    emitValue(obj) {
      for (const key in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, key)) {
          this.$set(this.queryData, key, obj[key])
        }
      }
    },
    change() {
    },
    btnEvent(item) {
      if (item.ifDialog) {
        this.$emit('dialogEvent', false, item)
      } else {
        this.$emit('apiEvent', item)
      }
    },
    // search() {
      
    //    Object.keys(this.$refs).forEach(refName => {
    // if (refName.startsWith('inputGroup_')) {
    //     const component = this.$refs[refName]
    //     console.log("component.emit_data", component.emit_data)
    //     if (component && component.emit_data) {
    //       for (const key in component.emit_data) {
    //         this.$set(this.queryData, key, component.emit_data[key])
    //       }
    //     }
    //   }
    // })
    //   this.$emit('searchEvent', false)
    // },
    search() {
  Object.keys(this.$refs).forEach(refName => {
    if (refName.startsWith('inputGroup_')) {
      const component = this.$refs[refName]
      // 如果是数组（多个同名 ref）
      const groupArray = Array.isArray(component) ? component : [component]
      groupArray.forEach(comp => {
        if (comp && comp.emit_data) {
          for (const key in comp.emit_data) {
            this.$set(this.queryData, key, comp.emit_data[key])
          }
        }
      })
    }
  })
  this.$emit('searchEvent', false)
}

  },
  beforeDestroy() {
    console.log("被销毁了组件")
    this.queryData = {}
  },
}
</script>

<style lang="less">
.user-search {
  .common-input {
    .el-input__inner {
      height: 41.2px !important;
    }
  }
}
</style>
